<?php

	/** 
	 * encapsulate methods for the table 'o_cre_refs'
	 */
	class Ref_Oc extends Model_Abstract{
		
		public function add($o_id, $cre_id){
			try{
				$sql = 'insert into o_cre_refs set o_id=?, cre_id=?';
				$result = $this->_connection->execute($sql, array($o_id, $cre_id));
				return $result;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function delete($id){
			try{
				$sql = 'delete from o_cre_refs where id=?';
				$result = $this->_connection->execute($sql, array($id));
				return $result;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		//delete the relation between the Offer and Creative by offer_id, creative_id
		public function deleteByOC($offer_id, $creative_id){
			try{
				$sql = 'delete from o_cre_refs where o_id=? and cre_id=?';
				$result = $this->_connection->execute($sql, array($offer_id, $creative_id));
				return $result;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function canDelete($o_id){
			try{
				$sql = 'select count(*) from o_cre_refs where o_id=?';
				$result = $this->_connection->query($sql, array($o_id));
				if($result && $result>1)
					return true;
				return false;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function cloneRef($o_id, $new){
			try{
				$sql = 'select cre_id from o_cre_refs where o_id=?';
				$result = $this->_connection->query($sql, array($o_id));
				if($result){
					foreach ($result as $row){
						$success = $this->add($new, $row['cre_id']);
						if(!$success)
							return false;
					}
				}
				return true;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function getRelatedCreativesByOfferId($offerId){
			try{
				$sql = 'select cre_id from o_cre_refs where o_id=?';
				$result = $this->_connection->query($sql, array($offerId));
				if($result){
					$creativeIds = array();
					foreach ($result as $creative){
						$creativeIds[] = $creative['cre_id'];	
					}
					return $creativeIds;
				}
				return NULL;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
	}